﻿import React, { useState } from 'react';
import { Button, Input, Upload, message, Image } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import '../css/VideoUploadPage.css';
import axios from 'axios';
import styled from 'styled-components';


const { Dragger } = Upload;

const CarPlate = () => {
  const [videoUrl, setVideoUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const [frameData, setFrameData] = useState({});
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [imgurl, setImgurl] = useState('');


  const handleVideoChange = (info) => {
    console.log(info);
    info.file.status = 'done';
  };

  const handleUrlChange = (e) => {
    setVideoUrl(e.target.value);
  };

  const startButtonHandler = () => {
    if (videoUrl || fileList.length > 0) {
      message.success('视频已准备好播放');
      console.log(fileList);
    } else {
      message.error('请上传视频或输入视频流地址');
    }
  };

  const customRequest = ({ file }) => {
    setTimeout(() => {
      file.status = 'done';
      file.response = {};
      // 更新文件列表
      setFileList([...fileList, file]);
    }, 1000);
  };

  async function uploadAndProcessVideo() {
    setLoading(true);
    const formData = new FormData();
    formData.append('video', fileList[0]);
    console.log(fileList[0]);
    try {
      // 发送视频文件到服务器
      const response = await fetch('http://localhost:5000/video_car', {
        method: 'POST',
        body: formData
      });

      if (!response.ok) {
        throw new Error(`HTTP 错误！状态: ${response.status}`);
      }

      console.log('收到响应:', response);
      setLoading(false);
      setLoaded(true);

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let buffer = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        let boundaryIndex;

        while ((boundaryIndex = buffer.indexOf('--frame')) !== -1) {
          const chunk = buffer.slice(0, boundaryIndex).trim();
          buffer = buffer.slice(boundaryIndex + '--frame'.length).trim();

          if (chunk) {
            const headerEndIndex = chunk.indexOf('\r\n\r\n');
            if (headerEndIndex !== -1) {
              const jsonPart = chunk.slice(headerEndIndex + 4);
              try {
                const totaldata = JSON.parse(jsonPart);

                // let tmpobj = {
                //   'person': 0,
                //   'car': 0,
                // };

                // for (let bbox of totaldata['bboxes']) {
                //   tmpobj[bbox[4]] += 1;
                // }

                // setFrameData(tmpobj);
                // setPersonData(prevData => [...prevData, tmpobj['person']]);
                // setCarData(prevData => [...prevData, tmpobj['car']]);
                setImgurl(totaldata['frame']);
              } catch (e) {
                console.error('解析JSON数据时出错:', e);
              }
            }
          }
        }
      }

    } catch (error) {
      console.error('Error uploading and processing video:', error);
    }
  }


  return (
    <>
      {
        !loaded ?
          <div className="container">
            <div className="content">
              <h1 className="title">上传视频或输入视频流地址</h1>
              <Input
                placeholder="输入视频流地址"
                value={videoUrl}
                onChange={handleUrlChange}
                className="input-url"
              />
              <Dragger
                customRequest={customRequest}
                onChange={handleVideoChange}
                style={{
                  marginBottom: 15,
                }}
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">点击或拖拽视频到此</p>
                <p className="ant-upload-hint">
                  支持单个或批量上传。
                </p>
              </Dragger>
              <Button
                type="primary"
                size="large"
                onClick={uploadAndProcessVideo}
                className="start-button"
                style={{
                  marginTop: 15
                }}
                loading={loading}
              >
                开始
              </Button>
            </div>
          </div> :
          <div className="container" style={{
            flexDirection: 'column',
            display: 'flex',
          }}>
            <div className="top-row">
              <div className="left-image" style={{
                border: '1px solid #ccc',
              }}>
                <img src={imgurl} alt="Example Image" style={{ width: '100%' }} />
              </div>
            </div>
          </div>
      }

    </>
  );
};

export default CarPlate;